/* Copyright 2014 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/

package com.gp.newsstand.auth;

import com.google.common.base.Strings;
import com.google.common.net.UrlEscapers;

import com.gp.newsstand.auth.client.GpAuthClient;
import com.gp.newsstand.auth.client.GpException;

import org.apache.http.client.utils.URIBuilder;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class GpLoginServlet extends HttpServlet {
  private static final Logger logger = Logger.getLogger(GpLoginServlet.class.getName());

  private String getContinueUrl(HttpServletRequest req) {
    String continueUrl = req.getParameter("continueUrl");
    continueUrl = Strings.nullToEmpty(continueUrl);
    if (!continueUrl.startsWith("http://") && !continueUrl.startsWith("https://")) {
      throw new IllegalArgumentException("invalid continue url");
    }
    return continueUrl;
  }

  private void setupJsp(HttpServletRequest req) throws GpException {
    String continueUrl = getContinueUrl(req);
    try {
      URIBuilder uri = new URIBuilder(continueUrl);
      uri.addParameter("token", "cancel");
      req.setAttribute("cancelUrl", uri.toString());
    } catch (URISyntaxException e) {
      throw new GpException("invalid continueUrl", e);
    }
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    try {
      setupJsp(req);
      req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
    } catch (GpException e) {
      throw new IOException(e);
    }
  }


  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    String name = req.getParameter("name");
    String password = req.getParameter("password");
    boolean redirectDone = false;
    try {
      setupJsp(req);
      GpAuthClient client = new GpAuthClient();
      GpAuthClient.Response response = client.authentication(name, password);
      if (response.success) {
        String continueUrl = getContinueUrl(req);
        URIBuilder uri = new URIBuilder(continueUrl);
        uri.addParameter("token", response.token);
        String url = uri.toString();
        resp.sendRedirect(url);
        redirectDone = true;
      } else {
        req.setAttribute("message", response.reason);
      }
    } catch (Throwable e) {
      logger.log(Level.WARNING, "error", e);
      req.setAttribute("message", "Error");
    }
    if (!redirectDone) {
      req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
    }
  }
}
